package com.winz.cultureapp.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.winz.cultureapp.R;
import com.winz.cultureapp.base.BaseAppCompatActivity;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.BookFixBean;
import com.winz.cultureapp.fragment.GetPictureFragment;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.RequestFactory;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.winz.cultureapp.utils.SharePrefsUtil;
import com.winz.cultureapp.widge.TimerSelector;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 实名认证
 */
public class RealNameAuthenActivity extends BaseAppCompatActivity implements TimerSelector.OkClickListener {
    private static final int START_TIME = 0x000001;
    private static final int END_TIME = 0x000002;
    private static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    private static final int REQUEST_PERMISSION_CODE = 267;
    private static final int PIC_UP = 0x0011; // 正面照
    private static final int PIC_DOWN = 0x0012; // 背面照

    @BindView(R.id.tv_top_title)
    TextView mTv_top_title;
    @BindView(R.id.et_name)
    EditText mEt_name;
    @BindView(R.id.et_phone)
    EditText mEt_phone;

    @BindView(R.id.iv_up)
    ImageView mIv_up;
    @BindView(R.id.iv_down)
    ImageView mIv_down;
    @BindView(R.id.tv_right)
    TextView mTv_right;
    @BindView(R.id.tv_start)
    TextView mTv_start;
    @BindView(R.id.tv_end)
    TextView mTv_end;
    @BindView(R.id.et_idcard)
    EditText mEt_idcard;

    Handler handler = new Handler();

    private TimerSelector ts_birht;
    private String startDate; // 身份证有效期开始时间
    private String endDate; // 结束时间
    private long start;
    private long end;

    private PopupWindow pop = null;
    private LinearLayout ll_popup;
    private GetPictureFragment getPicture;

    private int isFlag; // 拍照类型

    private String upPath ;
    private String downPath ;

    private GetPictureFragment.OnGetPictureListener mOnGetPictureListener = new GetPictureFragment.OnGetPictureListener() {

        @Override
        public void onComplete(String result) {
            try {
                getPicture.dismiss();
                Logger.e(result);

                Bitmap bitmap = BitmapFactory.decodeFile(result);
                if (isFlag == PIC_UP) {
                    mIv_up.setImageBitmap(bitmap);
                    upPath = result;
                } else {
                    mIv_down.setImageBitmap(bitmap);
                    downPath = result;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onCancel() {
            getPicture.dismiss();
        }
    };

    @Override
    protected int contentView() {
        return R.layout.activity_real_name;
    }

    @Override
    protected void initViews() {
        mTv_top_title.setText(getString(R.string.certification_item1));
        mTv_right.setText("保存");
        mTv_right.setVisibility(View.VISIBLE);
        ts_birht = new TimerSelector(this, "yyyy年MM月dd日");
        ts_birht.setOkClickListener(this);
        iniPop();
    }

    private void iniPop() {
        pop = new PopupWindow(this);

        View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);

        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);

        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //检查是否获得写入权限，未获得则向用户请求
                if (ActivityCompat.checkSelfPermission(RealNameAuthenActivity.this, PERMISSION_CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //未获得，向用户请求
                    Log.d("Register", "无读写权限，开始请求权限。");
                    ActivityCompat.requestPermissions(RealNameAuthenActivity.this, new String[]
                            {PERMISSION_CAMERA, PERMISSION_WRITE_STORAGE}, REQUEST_PERMISSION_CODE);
                } else {
                    Log.d("Register", "有读写权限，准备启动相机。");
                    photo();
                }

                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                /**
                 * 打开相册
                 */
                openAlbum();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
    }

    /**
     * 拍照
     */
    private void photo() {
        //启动照相机
        getPicture = GetPictureFragment.newInstance(GetPictureFragment.TYPE_REGIST, 480, 290, true);
        getPicture.setOnGetPictureListener(mOnGetPictureListener);
        getPicture.show(getSupportFragmentManager(), "tag");
//        getPicture.setIsNeed(false);


    }

    /**
     * 返回用户是否允许权限的结果，并处理
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResult) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResult);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户允许
                Logger.i("Register", "用户已允许权限，准备启动相机。");
                //启动照相机
                photo();
            } else {
                //用户拒绝
                Logger.i("Register", "用户已拒绝权限，程序终止。");
                showMsg("您拒绝本应用使用相机，请在设置权限中允许使用相机功能！！！！");
            }
        }
    }


    /**
     * 打开相册
     */
    private void openAlbum() {
        getPicture = GetPictureFragment.newInstance(GetPictureFragment.TYPE_REGIST, 480, 290, false);
        getPicture.setOnGetPictureListener(mOnGetPictureListener);
        getPicture.show(getSupportFragmentManager(), "tag");
//        getPicture.setIsNeed(false);
    }

    /**
     * 时间选择器
     *
     * @param view
     * @param date
     * @param time
     * @param flag
     */
    @Override
    public void okClick(View view, String date, long time, int flag) {
        if (flag == START_TIME) {
            mTv_start.setText(date);
            startDate = date;
            start = time;
        }else{
            mTv_end.setText(date);
            endDate = date;
            end = time;
        }
    }

    @OnClick({R.id.fl_back, R.id.tv_start,R.id.tv_end, R.id.iv_up, R.id.iv_down,R.id.rl_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_back:
                finish();
                break;
            case R.id.tv_start:
                ts_birht.show(mTv_start, START_TIME);
                break;
            case R.id.tv_end:
                ts_birht.show(mTv_end, END_TIME);
                break;
            case R.id.iv_up:
                isFlag = PIC_UP;
                ll_popup.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.activity_translate_in));
                pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.iv_down:
                isFlag = PIC_DOWN;
                ll_popup.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.activity_translate_in));
                pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.rl_right:
                if (isAllRight())
                submit();
                break;
        }
    }

    private boolean isAllRight() {
        if (TextUtils.isEmpty(getEditTextStr(mEt_name))){
            showMsg("请输入真实姓名");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_phone))){
            showMsg("请输入手机号码");
            return false;
        }
        if (TextUtils.isEmpty(getEditTextStr(mEt_idcard))){
            showMsg("请输入身份证号码");
            return false;
        }
        if (TextUtils.isEmpty(startDate)){
            showMsg("请选择身份有效期开始时间");
            return false;
        }
        if (TextUtils.isEmpty(endDate)){
            showMsg("请选择身份有效期结束时间");
            return false;
        }
        if (TextUtils.isEmpty(upPath)){
            showMsg("请上传身份证正面照");
            return false;
        }
        if (TextUtils.isEmpty(downPath)){
            showMsg("请上传身份证背面照");
            return false;
        }
        return true;
    }

    private void submit() {
        showProgressDialog();
        HttpUitls.onPostByToken("user_auth",
                SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN),
                RequestFactory.getInstance().user_auth(getEditTextStr(mEt_name),
                        getEditTextStr(mEt_phone),
                        getEditTextStr(mEt_idcard),
                        startDate,
                        endDate,
                        new File(upPath),
                        new File(downPath)),
                new OnResponeListener<BookFixBean>() {
            @Override
            public void onSuccess(BookFixBean bean) {
                Logger.d("user_auth==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0) {
                    showMsg("保存成功");
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    },500);
                }else{
                    showMsg(bean.msg);
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                Logger.d("user_auth==>>", error);
                dismissProgressDialog();
            }
        });
    }

}
